package com.igeek.service;

import com.igeek.dao.OrderDao;
import com.igeek.domain.Order;
import com.igeek.domain.OrderItem;
import com.igeek.utils.JDBCTools;
import org.apache.commons.dbutils.DbUtils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author jerryHe
 * @create 2019-10-12 10:06
 */
public class OrderService {
    OrderDao orderDao = new OrderDao();
    public void save(Order order) {
        //保存2个表，需要考虑事务操作
        Connection conn = null;
        try{
            //1.获取连接
            conn = JDBCTools.getConnection();
            //2.把连接放入ThreadLocal
            JDBCTools.threadLocal.set(conn);
            //3.开启事务
            conn.setAutoCommit(false);
            //4.执行sql
            orderDao.saveOrder(order);//插入订单表
            //遍历order中的orderitem，一条条的插入订单详情
            for(OrderItem item : order.getOrderItems()){
                orderDao.saveOrderItem(item);
            }
            //5.提交事务
            conn.commit();
        }catch (Exception e){
            //6.回滚
            DbUtils.rollbackAndCloseQuietly(conn);
            e.printStackTrace();
        }
    }

    public void update(Order order) {
        orderDao.update(order);
    }
}
